import Hapi from "@hapi/hapi";
import type { ServerOptions, Request } from "@hapi/hapi";
import mongoose from "mongoose";
import router from "./router";
import { User } from "./model/index";
import * as HapiSwagger from "hapi-swagger";
import Inert from "@hapi/inert";
import Vision from "@hapi/vision";
mongoose.connect("mongodb://127.0.0.1:27017/admin");

const config: ServerOptions = {
  port: 7070,
  host: "0.0.0.0",
};
//校验用户token
const validate = async (decoded: any, request: any, h: any) => {
  request.userId = decoded.userId;
  const user = await User.find({ _id: decoded.userId });
  if (!user) {
    return { isValid: false };
  }
  return { isValid: true };
};
//插件使用jwt
const plugin = {
  name: "auth",
  register: async (server: any, options: any) => {
    await server.register(require("hapi-auth-jwt2"));
    server.auth.strategy("jwt", "jwt", {
      key: options.secret,
      validate: validate,
      verifyOptions: { algorithms: ["HS256"] },
    });

    server.auth.default("jwt");
  },
};

const swaggerOptions: HapiSwagger.RegisterOptions = {
  info: {
    title: "Test API Documentation",
    version: "1.0.0",
  },
  swaggerUI: true,
  payloadType: "form",
  securityDefinitions: {
    apiKey: {
      type: "apiKey",
      name: "Authorization",
      in: "header",
    },
  },
};

const plugins = [
  {
    plugin: plugin,
    options: { secret: "123456" },
  },
  {
    plugin: Inert,
  },
  {
    plugin: Vision,
  },
  {
    plugin: HapiSwagger,
    options: swaggerOptions,
  },
];
//初始化
const init = async () => {
  const server = Hapi.server(config);
  await server.register(plugins);

  server.route(router);

  await server.start();
  console.log("Server running on %s", server.info.uri);
};

process.on("unhandledRejection", (err) => {
  console.log(err);
  process.exit(1);
});

init();
